package cn.wangkai.peanut.commons.beanutils;

import java.sql.Timestamp;
import java.util.Date;

import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * //日期类型采用自定义转换
 * ConvertUtils.register(new DateConverter(), java.util.Date.class);
 * //日期类型采用自定义转换
 * ConvertUtils.register(new DateConverter(), java.sql.Date.class);
 * BeanUtils.copyProperties(personnel, personnelForm);
 * @author wangkai
 *
 */
public class TimestampConverter implements Converter {

	private static final Log log = LogFactory.getLog(TimestampConverter.class);
	
	public TimestampConverter() {
	}
	
	
	@SuppressWarnings("rawtypes")
	public Object convert(Class type, Object value) {
		log.info("type="+type+"||value="+value);
		if(value==null||StringUtils.isEmpty(String.valueOf(value))) {
			return null;
		}


        if (value instanceof Timestamp) {
            return (value);
        }
        
		if(value instanceof Date) {
			return new Timestamp(((Date)value).getTime());
		}
		
		if(value instanceof Long) {
			Long longValue = (Long) value;
			return new Timestamp(longValue.longValue());
		}
		
		try {
			return new Timestamp(DateUtils.parseDate(value.toString(), new String[] {"yyyy-MM-dd HH:mm:ss.SSS", "yyyy-MM-dd HH:mm:ss","yyyy-MM-dd HH:mm","yyyy-MM-dd"}).getTime());
			
		} catch (Exception e) {
			throw new ConversionException(e);
		}

	}
	
	public static void main(String[] args) {

	}

}
